//
//  BaseTextField.m
//  XYZKitDemo
//
//  Created by 谢英泽 on 2016/11/20.
//  Copyright © 2016年 谢英泽. All rights reserved.
//

#import "BaseTextField.h"

#pragma mark - XYZFormattter

@implementation XYZFormattter

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if(_formatType == FormatTypePhone) {
        return [self shouldChangePhone:textField shouldChangeCharactersInRange:range replacementString:string];
    } else if (_formatType == FormatTypePassword) {
         return [self shouldChangePassword:textField shouldChangeCharactersInRange:range replacementString:string];
    } else if(_formatType == FormatTypeCard) {
        return [self shouldChangeCard:textField shouldChangeCharactersInRange:range replacementString:string];
    } else if(_formatType == FormatTypeTelephone) {
        return [self shouldChangeTelephone:textField shouldChangeCharactersInRange:range replacementString:string];
    } else if(_formatType == FormatTypeIDCard) {
        return [self shouldChangeIDCard:textField shouldChangeCharactersInRange:range replacementString:string];
    } else if(_formatType == FormatTypeSms) {
        return [self shouldChangeSms:textField shouldChangeCharactersInRange:range replacementString:string];
    }
    return YES;
}

#pragma mark - TextFieldDelegate代理

-(BOOL)shouldChangePhone:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
//    __block NSString *text = [textField text];
//    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
//    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
//    if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
//        return NO;
//    }
//    text = [text stringByReplacingCharactersInRange:range withString:string];
//    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
//    NSString *newString = @"";
//    
//    
//    BOOL isFirstThree = YES;
//    int length = 4;
//    while (text.length > 0) {
//        NSString *subString = nil;
//        //第一次三位
//        if(isFirstThree)
//        {
//            length = 3;
//            isFirstThree = NO;
//        }else{
//            
//            length = 4;        }
//        subString = [text substringToIndex:MIN(text.length, length)];
//        
//        newString = [newString stringByAppendingString:subString];
//        if (subString.length == length) {
//            newString = [newString stringByAppendingString:@" "];
//        }
//        text = [text substringFromIndex:MIN(text.length, length)];
//    }
//    
//    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
//    //11为电话号码长度 2为空格
//    if (newString.length >= 14) {
//        return NO;
//    }
//    
//    [textField setText:newString];
//    return NO;
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    //检测是否为纯数字
    if ([self isPureInt:string]) {
        //添加空格，每4位之后，4组之后不加空格，格式为xxxx xxxx xxxx xxxx xxxx
//        if (textField.text.length % 5 == 4 && textField.text.length < 13) {
//            textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
//        }
        if (textField.text.length <= 3) {
            if (textField.text.length == 3) {
                textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
            }
        } else {
            if (textField.text.length % 5 == 3 && textField.text.length < 13) {
                textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
            }
        }
        //只要13位数字
        if ([toBeString length] > 11+2) {
            toBeString = [toBeString substringToIndex:11+2];
            textField.text = toBeString;
            [textField resignFirstResponder];
            return NO;
        }
    } else if ([string isEqualToString:@""]) { // 删除字符
        if ((textField.text.length - 1) % 5 == 4 && textField.text.length < 13) {
            textField.text = [textField.text substringToIndex:textField.text.length - 1];
        }
        return YES;
    } else {
        return NO;
    }
    return YES;
}

- (BOOL)isPureInt:(NSString *)string {
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

-(BOOL)shouldChangePassword:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    //修改后的字符串
    NSMutableString *modifiedString = [NSMutableString stringWithString:textField.text];
    [modifiedString replaceCharactersInRange:range withString:string];
    
    //密码位数限制16位
    return modifiedString.length <= 16;
    return YES;
    
}

-(BOOL)shouldChangeCard:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSLog(@"%ld",(long)textField.tag);
//    if([textField isKindOfClass:[BaseTextField class]]){
//        
//        if(textField.tag==1001 && textField.text.length>0){
//            if([string isEqual:@""]|| string.length==0){
//                //银行卡修改次数
//                self.cnt_bank_modify=self.cnt_bank_modify+1;
//                NSLog(@"您修改了%ld次",self.cnt_bank_modify);
//                NSNumber *temp=[[NSUserDefaults standardUserDefaults]objectForKey:@"cnt_bank_modify"];
//                NSInteger tempInt=[temp integerValue];
//                tempInt=tempInt+1;
//                NSNumber *tempnum=[NSNumber numberWithInteger:tempInt];
//                [[NSUserDefaults standardUserDefaults]setObject:tempnum forKey:@"cnt_bank_modify"];
//                NSNumber *temp2=[[NSUserDefaults standardUserDefaults]objectForKey:@"cnt_bank_modify"];
//                NSLog(@"最后保存的数据：%ld",[temp2 integerValue]);
//            }
//        }
//    }
    
    __block NSString *text = [textField text];
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
        return NO;
    }
    text = [text stringByReplacingCharactersInRange:range withString:string];
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *newString = @"";
    while (text.length > 0) {
        NSString *subString = [text substringToIndex:MIN(text.length, 4)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == 4) {
            newString = [newString stringByAppendingString:@" "];
        }
        text = [text substringFromIndex:MIN(text.length, 4)];
    }
    
    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
    //银行卡16-19位，
    //4*4 + 4 + 3
    if (newString.length >= 24) {
        return NO;
    }
    [textField setText:newString];
    return NO;
}

-(BOOL)shouldChangeTelephone:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.tag==101 && textField.text.length>0) {
        //        static int cnt_supinfo_modif;
        if([string isEqual:@""]|| string.length==0){
            //其他信息修改次数
            //cnt_supinfo_modif=cnt_supinfo_modif+1;
            
            NSNumber *temp=[[NSUserDefaults standardUserDefaults]objectForKey:@"cnt_supinfo_modif"];
            NSInteger tempInt=[temp integerValue];
            tempInt=tempInt+1;
            NSNumber *tempnum=[NSNumber numberWithInteger:tempInt];
            [[NSUserDefaults standardUserDefaults]setObject:tempnum forKey:@"cnt_supinfo_modif"];
        }
    }
    
    __block NSString *text = [textField text];
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
        return NO;
    }
    text = [text stringByReplacingCharactersInRange:range withString:string];
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *newString = @"";
    
    if(text.length<=2) {
        [textField setText:text];
        return NO;
    }
    
    NSString* firstNumber= [text substringToIndex:1];
    NSString* secondNumber = [[text substringFromIndex:1]substringToIndex:1];
    BOOL isDicstrict = YES;
    int districtLength = 3;
    int length = 4;
    while (text.length > 0) {
        NSString *subString = nil;
        //第一次三位
        if(isDicstrict) {
            //表示国内电话
            if([firstNumber isEqualToString:@"0"]) {
                if ([secondNumber isEqualToString:@"1"] || [secondNumber isEqualToString:@"2"]) {
                    length = 3;
                } else {
                    length = 4;
                }
            } else {
                //国外电话
                length = 3;
            }
            isDicstrict = NO;
            districtLength = length;
        } else {
            length = 8;
        }
        subString = [text substringToIndex:MIN(text.length, length)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == length) {
            newString = [newString stringByAppendingString:@" "];
        }
        text = [text substringFromIndex:MIN(text.length, length)];
    }
    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
    //11为电话号码长度 2为空格
    if (newString.length >= districtLength+2+13) {
        return NO;
    }
    [textField setText:newString];
    return NO;
}

-(BOOL)shouldChangeIDCard:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    __block NSString *text = [textField text];
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
        return NO;
    }
    text = [text stringByReplacingCharactersInRange:range withString:string];
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *newString = @"";
    
    
    BOOL isFirstSix = YES;
    int length = 4;
    while (text.length > 0) {
        NSString *subString = nil;
        //第一次三位
        if(isFirstSix) {
            length = 6;
            isFirstSix = NO;
        } else {
            length = 4;
        }
        subString = [text substringToIndex:MIN(text.length, length)];
        
        newString = [newString stringByAppendingString:subString];
        if (subString.length == length) {
            newString = [newString stringByAppendingString:@" "];
        }
        text = [text substringFromIndex:MIN(text.length, length)];
    }
    
    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
    //11为电话号码长度 2为空格
    if (newString.length >= 22) {
        return NO;
    }
    [textField setText:newString];
    return NO;
}

-(BOOL)shouldChangeSms:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
//    __block NSString *text = [textField text];
//    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
//    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
//    if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
//        return NO;
//    }
//    text = [text stringByReplacingCharactersInRange:range withString:string];
//    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
//    NSString *newString = @"";
//    
//    
//    int length = 3;
//    while (text.length > 0) {
//        NSString *subString = nil;
//        length = 3;
//        subString = [text substringToIndex:MIN(text.length, length)];
//        
//        newString = [newString stringByAppendingString:subString];
//        if (subString.length == length) {
//            newString = [newString stringByAppendingString:@" "];
//        }
//        text = [text substringFromIndex:MIN(text.length, length)];
//    }
//    
//    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
//    //11为电话号码长度 2为空格
//    if (newString.length >= 8) {
//        return NO;
//    }
//    
//    [textField setText:newString];
//    return NO;
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    //检测是否为纯数字
    if ([self isPureInt:string]) {
        //添加空格，每4位之后，4组之后不加空格，格式为xxx xxx
        if(textField.text.length <= 3){
            if (textField.text.length == 3) {
                textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
            }
        }else{
            if (textField.text.length % 4 == 3 && textField.text.length < 7) {
                textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
            }
        }
        //只要13位数字
        if ([toBeString length] > 6+1)
        {
            toBeString = [toBeString substringToIndex:6+1];
            textField.text = toBeString;
            [textField resignFirstResponder];
            return NO;
        }
    }
    else if ([string isEqualToString:@""]) { // 删除字符
        if ((textField.text.length - 1) % 5 == 4 && textField.text.length < 7) {
            textField.text = [textField.text substringToIndex:textField.text.length - 1];
        }
        return YES;
    }
    else{
        return NO;
    }
    return YES;
}

@end

#pragma mark - BaseTextField

@interface BaseTextField ()

@property(nonatomic,retain) XYZFormattter*   formatter;

@property (nonatomic, strong) UIView *paddingView;

@end

@implementation BaseTextField

- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self initSelf];
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initSelf];
    }
    return self;
}

- (void)initSelf {
    //输入文字偏移
    _isNeedSpacing = YES;
    
    //设置placeholder向右偏移
    [self initTextFieldLeftView];

    //监听输入
    [self addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [self addTarget:self action:@selector(textFieldEditingDidBegin:) forControlEvents:UIControlEventEditingDidBegin];
    [self addTarget:self action:@selector(textFieldEditingDidEnd:) forControlEvents:UIControlEventEditingDidEnd];
}

- (void)initTextFieldLeftView {
    if (_isNeedSpacing) {
        self.leftView = self.paddingView;
        self.leftViewMode = UITextFieldViewModeAlways;
    }else{
        self.leftView = nil;
    }
}

#pragma mark - 输入框样式

/**
 输入框样式

 @param formatType 跟输入框样式类型
 */
-(void)setFormatType:(FormatType)formatType {
    _formatType = formatType;
    
    if(formatType == FormatTypePhone)
        self.keyboardType = UIKeyboardTypePhonePad;
    else if(formatType == FormatTypeCard)
        self.keyboardType = UIKeyboardTypeNumberPad;
    else if(formatType == FormatTypeTelephone)
        self.keyboardType = UIKeyboardTypeNumberPad;
    else if(formatType == FormatTypeSms)
        self.keyboardType = UIKeyboardTypePhonePad;
    [self.formatter setFormatType:formatType];
    self.delegate = self.formatter;
}

/**
 输入框样式
 
 @param text 设置输入框文字
 */
-(void)setFormatText:(NSString *)text {
    if (_formatType == FormatTypeNone) {
        [super setText:text];
    } else if (_formatType == FormatTypePhone) {
        [super setText:[self formatTextForPhone:text]];
    } else if (_formatType == FormatTypePassword) {
        [super setText:[self formatTextForPassword:text]];
    } else if(_formatType == FormatTypeCard) {
        [super setText:[self formatTextForCard:text]];
    } else if(_formatType == FormatTypeTelephone) {
        [super setText:[self formatTextForTelephone:text]];
    } else if(_formatType == FormatTypeIDCard) {
        [super setText:[self formatTextForIDCard:text]];
    } else if(_formatType == FormatTypeSms) {
        [super setText:[self formatTextForIDCard:text]];
    }
}


/**
 输入框样式

 @param srcText 设置输入框文字
 @return 手机号码格式
 */
-(NSString*)formatTextForPhone:(NSString*)srcText {
    NSMutableString* str = [srcText mutableCopy];
    if(str.length>11) {
        NSRange range;
        range.location = 11;
        range.length = str.length-11;
        [str deleteCharactersInRange:range];
        [str insertString:@" " atIndex:7];
        [str insertString:@" " atIndex:3];
    } else if(str.length>=8) {
        [str insertString:@" " atIndex:7];
        [str insertString:@" " atIndex:3];
    } else if(str.length>=4) {
        [str insertString:@" " atIndex:3];
    }
    return str;
}

/**
 输入框样式

 @param srcText 设置输入框文字
 @return 密码格式
 */
-(NSString*)formatTextForPassword:(NSString*)srcText {
    NSMutableString* str = [srcText mutableCopy];
    if(str.length>16) {
        NSRange range;
        range.location = 16;
        range.length = str.length-16;
        [str deleteCharactersInRange:range];
    }
    return str;
}

/**
 输入框样式

 @param srcText 设置输入框文字
 @return 银行卡号格式
 */
-(NSString*)formatTextForCard:(NSString*)srcText {
    //（16-19位）
    NSMutableString* str = [srcText mutableCopy];
    if(str.length>19) {
        NSRange range;
        range.location = 19;
        range.length = str.length-19;
        [str deleteCharactersInRange:range];
        [str insertString:@" " atIndex:16];
        [str insertString:@" " atIndex:12];
        [str insertString:@" " atIndex:8];
        [str insertString:@" " atIndex:4];
    } else if(str.length>16) {
        [str insertString:@" " atIndex:16];
        [str insertString:@" " atIndex:12];
        [str insertString:@" " atIndex:8];
        [str insertString:@" " atIndex:4];
    } else if(str.length>12) {
        [str insertString:@" " atIndex:12];
        [str insertString:@" " atIndex:8];
        [str insertString:@" " atIndex:4];
    } else if(str.length>8) {
        [str insertString:@" " atIndex:8];
        [str insertString:@" " atIndex:4];
    } else if(str.length>4) {
        [str insertString:@" " atIndex:4];
    }
    return str;
}

/**
 输入框样式

 @param srcText 设置输入框文字
 @return 电话号码格式
 */
-(NSString*)formatTextForTelephone:(NSString*)srcText {
    // 座机号：0755 88888888 0123
    NSMutableString* str = [srcText mutableCopy];
    NSString* firstNumber= [str substringToIndex:1];
    NSString* secondNumber = [[str substringFromIndex:1]substringToIndex:1];
    int districtLength = 3;
    //表示国内电话
    if([firstNumber isEqualToString:@"0"]) {
        if([secondNumber isEqualToString:@"1"] || [secondNumber isEqualToString:@"2"]) {
            districtLength = 3;
        } else {
            districtLength = 4;
        }
    } else {
        //国外电话
        districtLength = 3;
    }
    
    if(str.length>districtLength+8+4) {
        NSRange range;
        range.location = districtLength+8+4;
        range.length = str.length-range.location;
        [str deleteCharactersInRange:range];
        [str insertString:@" " atIndex:districtLength+8];
        [str insertString:@" " atIndex:districtLength];
    } else if(str.length>districtLength+8) {
        [str insertString:@" " atIndex:districtLength+8];
        [str insertString:@" " atIndex:districtLength];
    } else if (str.length>districtLength) {
        [str insertString:@" " atIndex:districtLength];
    }
    return str;
}

/**
 输入框样式

 @param srcText 设置输入框文字
 @return 身份证格式
 */
-(NSString*)formatTextForIDCard:(NSString*)srcText {
    NSMutableString* str = [srcText mutableCopy];
    if(str.length>21) {
        NSRange range;
        range.location = 21;
        range.length = str.length-21;
        [str deleteCharactersInRange:range];
        [str insertString:@" " atIndex:14];
        [str insertString:@" " atIndex:10];
        [str insertString:@" " atIndex:6];
    } else if(str.length>=8) {
        [str insertString:@" " atIndex:10];
        [str insertString:@" " atIndex:6];
    } else if(str.length>=4) {
        [str insertString:@" " atIndex:6];
    }
    return str;
}

/**
 将多余的间隔符去掉
 
 @return 不含间隔符的字符串
 */
-(NSString*)formatText {
    if(_formatType != FormatTypeNone) {
        NSString* text = [super text];
        return [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    return [super text];
}

#pragma mark - TextFieldDelegate
/**
 *  是否有输入
 */
- (void)textFieldDidChange:(UITextField *)textField {
    
    if (self.inputBlock) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (textField.text.length > 0) {
                //有输入
                self.inputBlock(YES);
            }else{
                //无输入
                self.inputBlock(NO);
            }
        });
    }
}

/**
 输入框的键盘遮挡处理
 
 @param textField 输入框编辑开始后，计算输入框是否与键盘有交叉重合地方，处理键盘遮挡的问题
 */
- (void)textFieldEditingDidBegin:(UITextField *)textField {
    //键盘默认高度为216，但无论系统自带键盘或者第三方键盘都自带键盘bar，大概为64像素宽
    //在本项目中，默认的起点是从(0,64)开始的，古需要减去64
    
    CGFloat offset = _currentHeight - ([UIScreen mainScreen].bounds.size.height - (216 + 64) - (64));
    if (offset > 0) {
        [UIView animateWithDuration:0.25 animations:^{
            [self.surpView setTransform:CGAffineTransformMakeTranslation(0,-offset)];
        }];
    }
}

/**
 输入框的键盘遮挡处理
 
 @param textField 输入框编辑结束后，位移偏移量回归原位
 */
- (void)textFieldEditingDidEnd:(UITextField *)textField {
    [UIView animateWithDuration:0.25 animations:^{
        self.surpView.transform = CGAffineTransformIdentity;
    }];
}

#pragma mark - Setter&&Getter

/**
 输入框向右偏移处理

 @param isNeedSpacing 是否需要设置输入框向右偏移
 */
- (void)setIsNeedSpacing:(BOOL)isNeedSpacing {
    _isNeedSpacing = isNeedSpacing;
    [self initTextFieldLeftView];
}

/**
 键盘遮挡处理

 @param currentHeight 输入框的高度
 */
- (void)setCurrentHeight:(CGFloat)currentHeight {
    _currentHeight = currentHeight;
}

/**
 键盘遮挡处理

 @param surpView 输入框父视图
 */
- (void)setSurpView:(UIView *)surpView {
    _surpView = surpView;
}


/**
 输入框向右偏移处理

 @return 间隔视图
 */
- (UIView *)paddingView {
    if (!_paddingView) {
        _paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
    }
    return _paddingView;
}

/**
 输入框样式
 
 @return 输入框格式对象
 */
-(XYZFormattter *)formatter {
    if(_formatter == nil) {
        _formatter = [[XYZFormattter alloc]init];
    }
    return _formatter;
}

@end
